package com.pocketmenu.persistence;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class OrderItemDataSource {
	
	// Database fields
	  private SQLiteDatabase database;
	  private SQLiteHelper dbHelper;
	  public static String[] allColumns = 
		  { SQLiteHelper.COLUMN_ID,			
			SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY,						
			SQLiteHelper.COLUMN_ORDER_ITEM_ID_ITEM,
			SQLiteHelper.COLUMN_ORDER_ITEM_ID_ORDER};

	  public OrderItemDataSource(Context context) {
	    dbHelper = new SQLiteHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	  }

	  public void close() {
	    dbHelper.close();
	  }

	  public OrderItem create(int quantity, int idItem, int idOrder) {
	    ContentValues values = new ContentValues();	    	   
	    values.put(SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY, quantity);	   
	    values.put(SQLiteHelper.COLUMN_ORDER_ITEM_ID_ITEM, idItem);
	    values.put(SQLiteHelper.COLUMN_ORDER_ITEM_ID_ORDER, idOrder);
	    
	    long insertId = database.insert(SQLiteHelper.TABLE_ORDER_ITEM, null,
	        values);
	    
	    Cursor cursor = database.query(SQLiteHelper.TABLE_ORDER_ITEM,
	        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
	        null, null, null);
	    cursor.moveToFirst();
	    OrderItem newTemp = cursorToObject(cursor);
	    cursor.close();
	    return newTemp;
	  }

	  public void delete(OrderItem toDelete) {
	    int id = toDelete.getId();
	    System.out.println("OrderItem deleted with id: " + id);
	    database.delete(SQLiteHelper.TABLE_ORDER_ITEM, SQLiteHelper.COLUMN_ID
	        + " = " + id, null);
	  }

	  public List<OrderItem> getAll() {
	    List<OrderItem> listTemp = new ArrayList<OrderItem>();

	    Cursor cursor = database.query(SQLiteHelper.TABLE_ORDER_ITEM,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      OrderItem temp = cursorToObject(cursor);
	      listTemp.add(temp);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return listTemp;
	  }
	  
	  public void deleteAll() {
		    
		    
		    database.delete(SQLiteHelper.TABLE_ORDER_ITEM,null, null);
		  }

		  
	  
	  
	  

	  public static OrderItem cursorToObject(Cursor cursor) {
	    OrderItem temp = new OrderItem();
	    temp.setId(cursor.getInt(0));		       
	    temp.setQuantity(cursor.getInt(1));	    
	    temp.setIdItem(cursor.getInt(2));
	    temp.setIdOrder(cursor.getInt(3));
	    return temp;
	  }
	  
	  
}
